package edu.polsl.bio.str.manager.dao;

import edu.polsl.bio.str.common.util.SerializationUtils;
import edu.polsl.bio.str.common.vo.JobData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.io.File;

/**
 * //todo class description
 * <p/>
 * Created on: Jun 14, 2011 6:12:49 PM <br/>
 * <a href="http://www.polsl.pl">www.polsl.pl</a>
 *
 * @author lukasz.olczak@polsl.pl
 */
public class JobDataDaoImpl implements JobDataDao {
  /**
   * slf4j Logger.
   */
  private static final Logger log = LoggerFactory.getLogger(JobDataDaoImpl.class.getName());

  private String jobDataDirPath;

  private File jobDataDir;

  @PostConstruct
  public void init() {
    jobDataDir = new File(jobDataDirPath);
    if (!jobDataDir.exists()) {
      log.debug("Making dir {}", jobDataDirPath);
      jobDataDir.mkdirs();
    }
  }

  @Override
  public byte[] getJobDataAsByteArray(String filePath) {
    return SerializationUtils.readAsByteArray(new File(filePath));
  }

  @Override
  public String saveJobData(JobData jobData) {
    try {
      File outFile = File.createTempFile("jobData_", ".bin", jobDataDir);
      SerializationUtils.saveAndCompressObject(jobData, outFile);
      return outFile.getAbsolutePath();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public void remove(String filePath) {
    log.debug("Removing {}", filePath);
    File file = new File(filePath);
    if (!file.delete()) {
      log.error("Cannot delete " + filePath);
    }
  }

  public void setJobDataDirPath(String jobDataDirPath) {
    this.jobDataDirPath = jobDataDirPath;
  }
}
